<template>
    <div class='container'>
        <el-dialog :title="title" :visible="showDialog" @close="btnCancel" width="400px">
            <el-form ref="perForm" :model="formDate" :rules="rules">
                <el-form-item label="所属学科" prop="subjectID" label-width="100px"  v-if="!dID.id">
                    <el-select v-model="formDate.subjectID" placeholder="请选择" style="width:100%">
                        <el-option v-for="(item,index) in SimpleList" :key="index" :value="item.value" :label="item.label"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="目录名称" label-width="100px" prop="directoryName">
                    <el-input v-model="formDate.directoryName" placeholder="请输入目录名称"/>
                </el-form-item>
            </el-form>
            <template v-slot:footer>
                <el-row type="flex" justify="end">
                    <el-button size="small" @click="btnCancel">取消</el-button>
                    <el-button type="primary" size="small" @click="btnOk">确定</el-button>
                </el-row>
            </template>
        </el-dialog>
    </div>
</template>

<script>

import { detail, update, add } from '@/api/hmmm/directorys'
import { simple } from '@/api/hmmm/subjects'

export default {
  name: 'DirectorysAdd',
  props: {
    showDialog: {
      type: Boolean,
      required: false
    }
  },
  data () {
    return {
      SimpleList: [],
      dID: this.$route.query,
      formDate: {
        subjectID: '',
        directoryName: ''
      },
      rules: {
        subjectID: [{ required: true, message: '请选择', trigger: 'blur' }],
        directoryName: [{ required: true, message: '请输入目录名称', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.getSimple()
  },
  computed: {
    title () {
      return this.formDate.id ? '修改目录' : '新增目录'
    }
  },
  methods: {
    btnCancel () {
      this.formDate = {
        subjectID: '',
        directoryName: ''
      }
      this.$refs.perForm.resetFields()
      this.$emit('update:showDialog', false)
    },
    async btnOk () {
      try {
        this.$refs.perForm.validate()
        if (this.formDate.id) {
          await update(this.formDate)
        } else {
          if (this.dID.id) {
            await add({ ...this.formDate, subjectID: Number(this.dID.id) })
          } else {
            await add(this.formDate)
          }
        }
        this.$message.success('操作成功')
        this.$emit('update')
        this.btnCancel()
      } catch (error) {
        console.log(error)
      }
    },
    async getDetail (id) {
      const { data } = await detail(id)
      this.formDate = data
    },
    async getSimple () {
      const { data } = await simple()
      this.SimpleList = data
    }
  }
}
</script>

<style scoped lang='less'></style>
